// server.js  
const Koa = require('koa');  
const Router = require('koa-router');  
const http = require('http');  
const { Server } = require("socket.io");  
const Mock = require('mockjs')  
const app = new Koa();  
const router = new Router();  
  
const server = http.createServer(app.callback());  
const io = new Server(server,{
  cors:{
    origin:"*"
  }
});  
  
io.on('connection', (socket) => {  
  console.log('a user connected');
 

    const ids = [1,2,3,4,5]
    const data1=[750, 300, 750, 650, 950]
    const data2=[140,80,70,110,130]
    const data3 = [1,1,1,1,1]
    const data4=[123,123,123,123,123]
    const data5 =[123,123,123,123,123]
    const code = 1;
  // 发送数据给前端  
  socket.emit('data', { message: 'Hello from Koa server!' });
  // 处理数组ids
  function updateids(array) {  
  // 假设我们想要替换数组中的每个元素为一个新的随机数  
  for (let i = 0; i < array.length; i++) {  
    array[i] = array[i] + 1;  
  }  
 return array
  }
  // 处理数组data1
  function updatedata1(array) {  
  // 假设我们想要替换数组中的每个元素为一个新的随机数  
  for (let i = 0; i < array.length; i++) {  
    // 生成一个0到100之间的随机整数作为示例  
    array[i] = Math.floor(Math.random() * 1000);  
  }  
  // 打印更新后的数组，或者你可以在这里添加其他逻辑来处理更新后的数组  
 return array
  }

    const frims = ['字节','抖音','阿里','腾讯','网易','百度','搜狗','蚂蚁','快手','当当网']
    
  const intervalId = setInterval(()=>{
    const frim = frims[Math.floor(Math.random()*frims.length)];
    const name = Mock.mock('@cname') // 生成随机中文名
    const wages = Mock.mock('@float(1, 500, 0, 2)') // 生成随机工资
    updateids(ids)
    updatedata1(data1)
    updatedata1(data2)
    updatedata1(data3)
    updatedata1(data4)
    updatedata1(data5)
    socket.emit('data', {ids: ids, data1: data1, data2: data2 ,data3: data3, data4: data4, data5: data5,name:name,frim:frim,wages:wages,code:code}); // 发送数据给客户端  
  },1000)
  


  socket.on('disconnect', () => {  
    console.log('user disconnected');
     clearInterval(intervalId);  
  });  
});  
  
const PORT = process.env.PORT || 8080;  
server.listen(PORT, () => {  
  console.log(`Server running on port ${PORT}`);  
});  
  
// 如果需要其他路由，可以添加在router中  
app.use(router.routes()).use(router.allowedMethods());



